package com.yanfan.energy.service.impl;

import com.yanfan.attach.domain.DeviceDetail;
import com.yanfan.attach.mapper.DeviceDetailMapper;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.domain.entity.SysUser;
import com.yanfan.common.core.page.PageDomain;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.energy.domain.*;
import com.yanfan.energy.domain.enums.EnergyType;
import com.yanfan.energy.mapper.SetEnergyAllocationDao;
import com.yanfan.energy.service.SetEnergyAllocationService;
import com.yanfan.iot.domain.Device;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 手动设置能源分配(SetEnergyAllocation)表服务实现类
 *
 * @author makejava
 * @since 2022-10-26 20:32:35
 */
@Slf4j
@Service("setEnergyAllocationService")
public class SetEnergyAllocationServiceImpl implements SetEnergyAllocationService {
    @Resource
    private SetEnergyAllocationDao setEnergyAllocationDao;

    @Autowired
    private DeviceDetailMapper deviceDetailMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public AjaxResult queryById(Integer id) {
        return AjaxResult.success(setEnergyAllocationDao.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param setEnergyAllocation 实例对象
     * @return 实例对象
     */
    @Override
    public SetEnergyAllocation insert(SetEnergyAllocation setEnergyAllocation) {
        this.setEnergyAllocationDao.insert(setEnergyAllocation);
        return setEnergyAllocation;
    }

    /**
     * 修改数据
     *
     * @param setEnergyAllocationdto 实例对象
     * @return 实例对象
     */
    @Override
    public AjaxResult update(SetEnergyAllocationDTO setEnergyAllocationdto) {
        if (ObjectUtils.isEmpty(setEnergyAllocationdto)) {
            return AjaxResult.error("入参异常，修改失败！");
        }
        SetEnergyAllocation setEnergyAllocation = new SetEnergyAllocation();
        setEnergyAllocation.setPercentage(setEnergyAllocationdto.getPercentage());
        setEnergyAllocation.setId(setEnergyAllocationdto.getId());
        setEnergyAllocation.setDeviceId(setEnergyAllocationdto.getDeviceId());
        setEnergyAllocation.setWorkshopId(setEnergyAllocationdto.getWorkshopId());
        setEnergyAllocationDao.update(setEnergyAllocation);

        return AjaxResult.success(queryById(setEnergyAllocationdto.getId()));
    }

    @Override
    public AjaxResult editList(List<SetEnergyAllocationDTO> setEnergyAllocationDto) {
        if (!setEnergyAllocationDto.isEmpty()) {
            return AjaxResult.error("入参异常，修改失败！");
        }
        setEnergyAllocationDto.stream().forEach(e -> {
            SetEnergyAllocation setEnergyAllocation = new SetEnergyAllocation();
            setEnergyAllocation.setPercentage(e.getPercentage());
            setEnergyAllocation.setId(e.getId());
            setEnergyAllocation.setDeviceId(e.getDeviceId());
            setEnergyAllocation.setWorkshopId(e.getWorkshopId());
            setEnergyAllocationDao.update(setEnergyAllocation);
        });

        return AjaxResult.success("修改成功");
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public AjaxResult deleteById(Integer id) {
        if (id == null || id == 0) {
            return AjaxResult.error("入参异常，删除失败！");
        }
        return AjaxResult.success(setEnergyAllocationDao.deleteById(id) > 0);
    }

    @Override
    public AjaxResult findEnergyAllocation(Integer[] equipments) {
        if (ObjectUtils.isEmpty(equipments)) {
            return AjaxResult.success(null);
        }
        return AjaxResult.success(setEnergyAllocationDao.selectequipmentEnergy(equipments));
    }

    @Override
    public AjaxResult findEnergyAllot(PageDomain pageDomain) {
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        DeviceDetail device = new DeviceDetail();
        List<DeviceAllotBody> deviceAllotBodies = new ArrayList<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (user.isAdmin()) {
            deviceAllotBodies = deviceDetailMapper
                    .selectDeviceList(device)
                    .stream()
                    .map(d -> new DeviceAllotBody(d.getDeviceId(), d.getDeviceName(), null))
                    .collect(Collectors.toList());
        }
        device.setTenantId(user.getUserId());
        deviceAllotBodies = deviceDetailMapper
                .selectDeviceList(device)
                .stream()
                .map(d -> new DeviceAllotBody(d.getDeviceId(), d.getDeviceName(), null))
                .collect(Collectors.toList());
        Integer total = deviceAllotBodies.size();
        if (!deviceAllotBodies.isEmpty()) {
            List<SetEnergyAllocations> list = setEnergyAllocationDao.selectequipmentEnergyByDeviceId();

            deviceAllotBodies.stream().forEach(d -> {
                List<SetEnergyAllocations> re = new ArrayList<>();
                list.stream().forEach(l -> {
                    if (d.getDeviceId().equals(l.getDeviceId())) {
                        re.add(l);
                        d.setSetEnergyAllocations(re);
                    } else {
                        d.setSetEnergyAllocations(new ArrayList<>());
                    }
                });
            });
            PageInfo pageInfo = new PageInfo<>(deviceAllotBodies
                                                       .stream()
                                                       .skip((pageNum - 1) * pageSize)
                                                       .limit(pageSize)
                                                       .collect(Collectors.toList()));
            pageInfo.setTotal(total);
            return AjaxResult.success(pageInfo);
        }
        PageInfo pageInfo = new PageInfo<>(deviceAllotBodies
                                                   .stream()
                                                   .skip((pageNum - 1) * pageSize)
                                                   .limit(pageSize)
                                                   .collect(Collectors.toList()));
        pageInfo.setTotal(total);
        return AjaxResult.success(pageInfo);
    }

    @Override
    public AjaxResult showEnergyType(Device device) {
        List<EnergyTypeDTO> list = new ArrayList<>();
        // 租户的权限
        List<Device> all = new ArrayList<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (user.isAdmin()) {
            all = deviceDetailMapper.findAllByUserId(null);
        } else {
            device.setTenantId(user.getUserId());
            all = deviceDetailMapper.findAllByUserId(user.getUserId().intValue());
        }

        // 限制中集集电的用户
        if (SecurityUtils.getUserId() == 256) {
            all = deviceDetailMapper.findAll(20);
        }

        if (all != null && all.size() > 0) {
            for (Device device1 : all) {
                EnergyTypeDTO energyTypeDTO = new EnergyTypeDTO();
                energyTypeDTO.setId(device1.getProductId().intValue());
                energyTypeDTO.setDeviceName(device1.getProductName());

                List<Device> devices = new ArrayList<>();
                if (user.isAdmin()) {
                    devices = deviceDetailMapper.selectDeviceByProductId(device1.getProductId(), null);
                } else {
                    devices = deviceDetailMapper.selectDeviceByProductId(device1.getProductId(), user.getUserId());
                }
                if (devices != null && devices.size() > 0) {
                    energyTypeDTO.setDeviceShortOutputs(devices);
                    energyTypeDTO.setCreateTime(devices.get(0).getCreateTime());
                }
                list.add(energyTypeDTO);
            }
        }

        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult add(SetEnergyAllocationDTO setEnergyAllocationdto) {
        if (ObjectUtils.isEmpty(setEnergyAllocationdto)) {
            return AjaxResult.error("入参有误");
        }

        // 车间去重
        for (Integer workshopId : setEnergyAllocationdto.getWorkshopIds()) {
            SetEnergyAllocation obj = setEnergyAllocationDao.queryByWorkshopIdAndDeviceId(workshopId, setEnergyAllocationdto.getDeviceId());
            if (ObjectUtils.isEmpty(obj)) {

                // 查询设备在哪些车间
                List<SetEnergyAllocation> setEnergyAllocationList = setEnergyAllocationDao.queryByDeviceId(setEnergyAllocationdto.getDeviceId());
                // 判断车间总百分比是否大于100
                int temp = 0;
                for (SetEnergyAllocation setEnergyAllocation : setEnergyAllocationList) {
                    temp += setEnergyAllocation.getPercentage().intValue();
                }
                // 小于100执行新增
                if (temp <= 100) {
                    //加车间
                    SetEnergyAllocation setEnergyAllocation = new SetEnergyAllocation();
                    setEnergyAllocation.setDeviceId(setEnergyAllocationdto.getDeviceId());
                    setEnergyAllocation.setPercentage(0.00);
                    setEnergyAllocation.setWorkshopId(workshopId);
                    setEnergyAllocationDao.insert(setEnergyAllocation);
                }
            }
        }
        return AjaxResult.success("成功！！！");
    }

    @Override
    public AjaxResult showType() {
        List<Map<Integer, String>> list = new ArrayList<>(10);
        for (EnergyType value : EnergyType.values()) {
            Map<Integer, String> map = new HashMap<>();
            map.put(value.getId(), value.getType());
            list.add(map);
        }
        return AjaxResult.success(list);
    }


}
